from sqlalchemy import Column
from werkzeug.datastructures import FileStorage

from apps.db import BaseModel, String
from apps.utils import curtime
from apps.utils.static_file import save_file


class File(BaseModel):
    __tablename__ = 'tb_file'
    file_name = Column(String)
    create_time = Column(String)
    history_id = Column(String)

    def __init__(self, *args, **kwargs):
        super(File, self).__init__()
        for attr, value in kwargs.items():
            if attr in self.__column_name_list__() and getattr(self, attr) is None:
                setattr(self, attr, value)

    @classmethod
    def save_file_bytes(cls, f: FileStorage, history_id =None):
        file = File(**{
            'file_name': f.filename,
            'create_time': curtime(),
            'history_id': history_id,
        }).save()
        save_file(f, file.id)
        return file
